<?php
/**
 *  * 系统-受国家计算机软件著作权保护 - !
 * =========================================================
 * Copy right 2018-2025 成都海之心科技有限公司, 保留所有权利。
 * ----------------------------------------------
 * 官方网址: http://www.ohyu.cn
 * 这不是一个自由软件！在未得到官方有效许可的前提下禁止对程序代码进行修改和使用。
 * 任何企业和个人不允许对程序代码以任何形式任何目的再发布。
 * =========================================================
 * User: ohyueo
 * Date: 2023/9/21
 * Time: 10:00
 */

namespace app\common;
use think\facade\Db;
use think\facade\Cache;
use think\facade\Log;

class TouTiao
{
    /**抖音调用凭证**/
    public function GetClientToken(){
        $data = array('status' => 0,'msg' => '未知错误');
        //获取缓存是否存在
        $access_token=Cache::get('toutiao_clienttoken');
        if(!$access_token){
            $params = [
                'client_key'       => 'awqgs9ynij5heqxc', //应用唯一标识
                'client_secret' => 'f9ef902f93082622589272ae6220a08e', //应用唯一标识对应的密钥
                'grant_type' => 'client_credential', //固定值
            ];
            $response=$this->post('https://open.douyin.com/oauth/client_token/', $params);
            if($response && $response['data'] && $response['data']['error_code']==0){
                $access_token=$response['data']['access_token'];
                Cache::set('toutiao_clienttoken', $access_token, 7000); //在7200秒之前7000秒过期
                $data['msg']='请求成功';
                $data['status']=1;
                $data['access_token']=$access_token;
            }else{
                Log::inf('access_token获取失败'.json_encode($response));
                $data['msg']='access_token获取失败';
                $data['status']=0;
            }
        }else{
            $data['access_token']=$access_token;
            $data['msg']='请求成功';
            $data['status']=1;
        }
        return $data;
    }
    /**
     * post request
     * @param string $uri
     * @param array $params
     * @param array $headers
     * @return string
     */
    private function post(string $uri, array $params = [], array $headers = [])
    {
        $headers[] = 'Content-type: application/json';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $uri);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $output = curl_exec($ch);
        curl_close($ch);
        return json_decode($output, true);
    }
    /**获取链接产生的二次网址**/
    function getMapUrl($url){
        $result = get_headers($url, true);
        return isset($result['Location'])? $result['Location'] : '';
    }
    /**发送get请求**/
    /**
     * @param $url
     * @param array $header
     * @return bool|string
     */
    function curl_get($url,$header = array()){
        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $url);
        //设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_HEADER, 0);
        // 超时设置,以秒为单位
        curl_setopt($curl, CURLOPT_TIMEOUT, 1);
        // 超时设置，以毫秒为单位
        // curl_setopt($curl, CURLOPT_TIMEOUT_MS, 500);
        // 设置请求头
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        //执行命令
        $data = curl_exec($curl);
        // 显示错误信息
        if (curl_error($curl)) {
            print "Error: " . curl_error($curl);
        } else {
            // 打印返回的内容
            curl_close($curl);
            return $data;
        }
    }
    /**团购核销 验券准备**/
    public function CertificatePreparation($codeurl,$code){
        $encrypted_data='';
        if($codeurl){
            $str=$this->getMapUrl($codeurl);
            if($str){
                $fru='object_id=';
                $data=explode('&',$str);
                if($data){
                    foreach ($data as $key=>$val){
                        if(strstr($val,$fru)){
                            $arr=explode('object_id=',$val);
                            if($arr && count($arr)>1){
                                $encrypted_data=$arr[1];
                            }
                        }
                    }
                }
            }
        }
        $accres=$this->GetClientToken();
        if($accres['status']!=1){
            return $accres;
        }else{
            $accetoken=$accres['access_token'];
        }
        // 请求头
        $headers[] = "content-type:multipart/form-data;"; // content-type
        $headers[] = "access-token:".$accetoken; // cooki
        if($encrypted_data){
            $url="https://open.douyin.com/goodlife/v1/fulfilment/certificate/prepare?encrypted_data=".$encrypted_data;
        }else if($code){
            $url="https://open.douyin.com/goodlife/v1/fulfilment/certificate/prepare?code=".$code;
        }else{
            Log::inf('券和二维码必需传一个');
            $data = array('status' => 0,'msg' => '券和二维码必需传一个');
            return $data;
        }
        $response = $this->curl_get($url,$headers);
        $response = json_decode($response,true);
        if($response && $response['data'] && $response['data']['error_code']==0){
            $verify_token=$response['data']['verify_token']; //验券的标识
            $certificates=$response['data']['certificates']; //团购票  列表
            $order_id=$response['data']['order_id'];//订单id
            $encrypted_codes=[]; //核券时候用到的 加密券码列表
            if($certificates){
                foreach ($certificates as $key=>$val){
                    array_push($encrypted_codes,$val['encrypted_code']);
                }
                if(1==2){ //这里是多个券  不是单个  所以不执行以下操作
                    $sku=$certificates['sku'];//商品sku
                    if($sku){
                        $title=$sku['title'];//团购名称
                        $groupon_type=$sku['groupon_type'];//团购类型（type=1团餐券; type=2代金券; type=3次卡）
                        $market_price=$sku['market_price'];//团购市场价
                        $sold_start_time=$sku['sold_start_time'];//团购售卖开始时间，时间戳，单位秒
                    }
                    $amount=$certificates['amount'];//券金额
                    if($amount){
                        $original_amount=$amount['original_amount'];//原始金额
                        $list_market_amount=$amount['list_market_amount'];//划线价
                        $pay_amount=$amount['pay_amount'];//用户实付金额
                        $merchant_ticket_amount=$amount['merchant_ticket_amount'];//商家营销金额
                        $payment_discount_amount=$amount['payment_discount_amount'];//支付优惠金额
                        $platform_discount_amount=$amount['platform_discount_amount'];//平台优惠金额
                    }
                }
            }
            $data = array('status' => 1,'msg' => '请求成功','verify_token'=>$verify_token,'encrypted_codes'=>$encrypted_codes,'order_id'=>$order_id);
            return $data;
        }else{
            Log::inf('准备验券接口错误'.json_encode($response));
            $data = array('status' => 0,'msg' => '准备验券接口错误');
            return $data;
        }
    }
    /**开始验券**/
    public function VerifyCertificate(){
        $code='101222799088738';//原始的抖音团购券码
        $url='';//https://v.douyin.com/eHHc1ft/';//从二维码解析出来的标识
        $poi_id='6601146476879939598';//门店ID
        $accres=$this->GetClientToken(); //获取 accetoken 调用获取抖音token方法
        if($accres['status']!=1){
            return $accres;
        }else{
            $accetoken=$accres['access_token'];
        }
        $res = $this->CertificatePreparation($url,$code);//调用验券接口
        if($res && $res['status']==1){
            $verify_token=$res['verify_token'];//一次验券的标识
            $encrypted_codes=$res['encrypted_codes'];//验券准备接口返回的加密抖音券码
            $params = [
                'verify_token'       => $verify_token, //一次验券的标识
                'poi_id' => $poi_id, //门店ID
                'encrypted_codes' => $encrypted_codes,//验券准备接口返回的加密抖音券码
            ];
            $headers[] = "access-token:".$accetoken; // cooki
            $response=$this->post('https://open.douyin.com/goodlife/v1/fulfilment/certificate/verify/', $params,$headers);
            if($response && $response['data'] && $response['data']['error_code']==0){

                //验券后还得存起来  不然无法查询券的状态
                echo "验券成功";
                var_dump($response);
            }else{
                echo "验券失败";
                var_dump($response);
            }
        }else{
            var_dump($res);
        }
    }
    /**券状态批量查询**/
    public function CertificateStatus(){
        $code='101222799088738';//原始的抖音团购券码
        $url='';//https://v.douyin.com/eHHc1ft/';//从二维码解析出来的标识
        $poi_id='6601146476879939598';//门店ID
        $accres=$this->GetClientToken(); //获取 accetoken 调用获取抖音token方法
        if($accres['status']!=1){
            return $accres;
        }else{
            $accetoken=$accres['access_token'];
        }
        $res = $this->CertificatePreparation($url,$code);//调用准备验券接口
        if($res && $res['status']==1){
            $verify_token=$res['verify_token'];//一次验券的标识
            $encrypted_codes=$res['encrypted_codes'];//验券准备接口返回的加密抖音券码
            $order_id=$res['order_id'];//订单id
            // 请求头
            $headers[] = "content-type:multipart/form-data;"; // content-type
            $headers[] = "access-token:".$accetoken; // cooki
            $url="https://open.douyin.com/goodlife/v1/fulfilment/certificate/query/?order_id=".$order_id;
            $response = $this->curl_get($url,$headers);
            $response = json_decode($response,true);
            if($response && $response['data'] && $response['data']['error_code']==0){
                $certificates=$response['data']['certificates'];
                foreach ($certificates as $key=>$val){
                    $title='';
                    $sku=$val['sku'];
                    $title.=$sku['title'];
                    $status=$val['status'];
                    $statustit=['初始状态','未使用','已使用','表示退款申请中（待审核）','退款成功','退款失败','退款中'];
                    echo $title.'-'.$statustit[$status];
                }
                var_dump($response);
            }else{
                echo "查询失败";
                var_dump($response);
            }
        }else{
            var_dump($res);
        }
    }
}